/*
 * 作者: junmu
 * 时间: 2025-07-22
 */
package com.hzbc.faceattendance.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class FileUploadUtil {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.upload-pic-dir}")
    private String uploadPicDir;

    public void HttpClientDownloader(String imageUrl, String fileName, int userPic) throws IOException, InterruptedException, URISyntaxException {

//        String imageUrl = "http://159.75.87.53:65105/picture/Streaming/tracks/803/?name=ch00008_010018500075520270003a7fd0003cac901051bf7bc7823c6800&size=2396";
        URI uri = new URI(imageUrl);
        URI newUri = new URI(
                uri.getScheme(),
                null,  // userInfo
                "159.75.87.53",  // host
                65105,  // port
                uri.getPath(),
                uri.getQuery(),
                uri.getFragment()
        );
        String fonalpicpath = (userPic == 0) ? uploadDir : uploadPicDir;
        String destinationFile = fonalpicpath + fileName;
        String newUrl = newUri.toString();
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(newUrl))
                .build();
        HttpResponse<Path> response = client.send(request,
                HttpResponse.BodyHandlers.ofFile(Paths.get(destinationFile)));

        System.out.println("图片下载完成，保存为: " + destinationFile);
    }

    public String getUploadDir() {
        return this.uploadDir;
    }

    public String uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IOException("Failed to store empty file");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String storedFilename = UUID.randomUUID() + fileExtension;

        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        Path filePath = uploadPath.resolve(storedFilename);
        file.transferTo(filePath);

        return storedFilename;
    }

    public boolean deleteFile(String filename) throws IOException {
        Path filePath = Paths.get(uploadDir).resolve(filename);
        return Files.deleteIfExists(filePath);
    }
}